import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { getCurrentUserUsingGet, userLogoutUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'

export const useUserStore = defineStore(
  'image-user',
  () => {
    const userInfo = ref<API.LoginUserVo>({})
    const token = ref<string>('')
    const searchPictureList = ref<API.SoImageSearchResult[]>([])

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
      // 调用接口获取用户信息
      const res: any = await getCurrentUserUsingGet()
      if (res.data.data) {
        setUserInfo(res.data.data)
      }
    }

    /**
     * 判断是否登录
     */
    const isLogin = computed(() => {
      return userInfo.value?.id
    })

    /**
     * 设置用户信息
     */
    const setUserInfo = (user: API.LoginUserVo) => {
      userInfo.value = user
    }

    /**
     * 删除用户信息
     */
    const removeUserInfo = async () => {
      userInfo.value = {}
      token.value = ''
      const res = await userLogoutUsingPost()
      if (res.data.code === 0 && res.data.data) {
        message.success('退出登录成功')
      }
    }

    // 设置图片信息
    const setSearchPictureList = (pictures: API.SoImageSearchResult[]) => {
      searchPictureList.value = pictures
    }

    // 获取图片信息
    const getSearchPictureList = () => {
      return searchPictureList.value
    }

    // 获取token
    const getToken = () => {
      return token.value
    }

    // 设置token
    const setToken = (t: string) => {
      token.value = t
    }


    return {
      setUserInfo,
      removeUserInfo,
      fetchUserInfo,
      userInfo,
      isLogin,
      setSearchPictureList,
      getSearchPictureList,
      getToken,
      setToken
    }
  },
  {
    persist: true,
  },
)
